package com.changgou.weixin;

import com.alibaba.fastjson.JSON;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

import java.security.KeyPair;

import java.security.interfaces.RSAPrivateKey;
import java.util.HashMap;
import java.util.Map;

/**
 * 微服务解析令牌
 */
public class CreateJwtTestDemo {

    @Test
    public void testCreateToken() {
        //加载证书
        ClassPathResource resource = new ClassPathResource("changgou.jks");
        //读取证书数据
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(resource, "changgou".toCharArray());
        KeyPair keyPair = keyStoreKeyFactory.getKeyPair("changgou", "changgou".toCharArray());
        //获取私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        //载荷
        Map<String, Object> payload = new HashMap<String, Object>();
        payload.put(" nikename", " tomcat");
        payload.put("address", "gy");
        payload.put("role", "admin,user");
        //创建令牌，需要私钥加盐[RSA算法]
        Jwt jwt = JwtHelper.encode(JSON.toJSONString(payload), new RsaSigner(privateKey));
//        获取令牌
        String token = jwt.getEncoded();
        System.out.println(token);
    }

    /**
     * 解析令牌
     */
    @Test
    public void testParscloken() {
        String token="";
        String publicKey="";
        Jwt jwt = JwtHelper.decodeAndVerify(token, new RsaVerifier(publicKey));
        String claims=jwt.getClaims();
        System.out.println(claims);
    }
}
